package com.limao.CacheManager;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.Hazelcast.Cache;
import com.Hazelcast.CacheFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.limao.DBDataClass.CrowdHomeCommendClass;
import com.limao.DBProvider.CrowdSysProjectProvider;
import com.limao.Tool.CacheClass;
import com.limao.cache.BasicModule;

public class CrowdHomeCommendCache  extends BasicModule{
	
	private CrowdSysProjectProvider provider;
	private String key="all";
	private static CrowdHomeCommendCache instance;
	private boolean flag;

    public static CrowdHomeCommendCache getInstance() {
        return instance;
    }
 
    private Cache<String, String> homeCommendCache;

    public CrowdHomeCommendCache() {
    	super("CrowdHomeCommendCache");
    	homeCommendCache = CacheFactory.createCache("sys_crows_HomeCommendCache");
    	
    	initProvider();
    	
    	new Thread()
    	{
    		public void run()
    		{
    			while(flag)
    			{
	    			ClearObjectCache();
	    			try {
						sleep(1*60*1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
    			}
    			
    		}
    		
    	}.start();
    }
    
    @Override
	public void start() {
        super.start();
        flag=true;
    }
       
    @Override
	public void stop() {
        super.stop();
        flag=false;
    }   
    
    @Override
	public void initialize() {
        super.initialize();
        instance=this;
    }
    

	
    public void ClearObjectCache()
    {
    	homeCommendCache.clear();
    }  
    
    
    public List<CrowdHomeCommendClass> Load_CrowdHomeCommend_All()
    {
     	List<CrowdHomeCommendClass> list=new ArrayList<CrowdHomeCommendClass>();
    	String jsonStr=homeCommendCache.get(key);
    	if(CacheClass.isEmpty(jsonStr))
    	{
    		list=provider.HomeCrowdSysProject();
    		if(list!=null && list.size()>0)
    		{
    			jsonStr=JSON.toJSONString(list);
    			homeCommendCache.put(key, jsonStr);
    		}
    	}
    	else
    	{
    		CrowdHomeCommendClass[] nodes = JSON.parseObject(jsonStr, new TypeReference<CrowdHomeCommendClass[]>(){});    
	        list.addAll(Arrays.asList(nodes));
    	}
     	return list;
    }
   
    
//******************************************************
    private void initProvider() {
        if (provider == null ) {
            try {
                provider =CrowdSysProjectProvider.getInstance();
            }
            catch (Exception e) {
            	e.printStackTrace();
            }
        }
    }
  
}


